<?php

namespace app\admin\model;

use app\service\Score;
use Exception;
use PDO;
use think\facade\Db;
use think\facade\Session;
use think\Model;

class Goods extends Model
{
  public function category()
  {
    return $this->hasOne(GoodsCategory::class, 'cid', 'cid');
  }
  public function fake()
  {
    return $this->hasMany(Fake::class, 'good_id', 'id');
  }
  /** 
   * 商品类型(提交成功后奖品发放形式0普通内容，1卡密发放，
   * 2增加用户的vip时长
   * 3参数提交（对应good_params表),3vip时长,用户组身份
   */
  public static function goodStockNeed()
  {
    // 系统商品（vip时长，)
    $goodCtn = self::where(['type' => 0, 'stock' => 0])->count();
    $goodVip = self::where(['type' => 2, 'stock' => 0])->count();
    $goodFake = self::where(['type' => 1])->select();
    $n = 0;
    foreach ($goodFake as $k => $v) {
      $fake = Fake::where(['good_id' => $v['id'], 'status' => 0])->select()->count();
      if ($fake == 0) 
        $n++;
    }
    return [
      'goodCtn' => $goodCtn,
      'goodVip' => $goodVip,
      'goodFake' => $n,
    ];
  }
  public static function list($param = [])
  {
    /* 商品类型(提交成功后奖品发放形式
      0普通内容，
      1卡密发放， 注意这个库存是得到卡密表对应的商品good_id获取条数决定
      2增加用户的vip时长
      3参数提交（对应good_params表),3vip时长,用户组身份 */
    $list = self::where($param)->with(['category'])->paginate();
    foreach ($list as $k => $v) {
      if ($v['type'] == 1) {
        $list[$k]['stock'] = Fake::where(['good_id' => $v['id'], 'status' => 0])->count();
      }
    }
    return $list;
  }
  // 商品列表数据处理
  public static function lisHandel($list)
  {
    foreach ($list as $k => $v) {
      if ($v['type'] == 1) {
        $list[$k]['stock'] = Fake::where(['good_id' => $v['id'], 'status' => 0])->count();
      }
    }
    return $list;
  }
  public static function pay($goodId, $user_id)
  {
    $data = self::where('id', $goodId);
    if ($data->findOrEmpty()->isEmpty()) return error('商品不存在');
    $goods = $data->find();
    if ($goods['type'] != 1) {
      if ($goods['stock'] == 0) return error('商品库存不足，请稍后尝试');
    } else {
      $fakeCount = Fake::where('good_id', $goodId)->count();
      if ($fakeCount == 0) return error('商品库存不足，请稍后尝试');
    }
    $order = [
      'good_id' => $goodId,
      'order_id' => date('YmdHis', time()) + random_int(1000, 99999),
      'user_id' => $user_id,
      'buy_num' => 1,
      'status' => 0,
      'create_time' => time()
    ];
    $orderLastId = Db::name('orders')->insertGetId($order);
    $pay = Score::compare($user_id, $goods['score']);
    if ($pay == 1) {
      try {
        $res = self::execGoods($goods, $user_id);
        if (is_object($res)) {
          // 减少库存
          self::where('id', $goods['id'])->dec('stock', 1)->update();
          Db::name('orders')->where('id', $orderLastId)->update(['status' => 1]);
          return $res;
        } else {
          // 卡密库存不足或其他原因
          Db::name('orders')->where('id', $orderLastId)->update(['status' => 2]);
          Score::add($user_id, $goods['score']);
        }
      } catch (Exception $e) {
        // return $e->getMessage();
        Db::name('orders')->where('id', $orderLastId)->update(['status' => 2]);
        Score::add($user_id, $goods['score']);
        return error('系统异常，请联系管理员处理！');
      }
    } else {
      $score = abs($pay);
      return error("积分不足，还差 $score 积分");
    }
  }
  public static function execGoods($data, $user_id = '')
  {
    $good_name = $data['good_name'];
    switch ($data['type']) {
      case 0:
        $content = $data['content'];
        $message = "恭喜您兑换【 $good_name 】成功 , 内容为[$content]";
        Msg::send(0, $user_id, ['content' => $message]);
        return success($message);
        break;
      case 1:
        $res = Fake::getFake(['good_id' => $data['id']]);
        $message = "恭喜您兑换【 $good_name 】成功 , 卡密已发至你的消息列表，请注意查看！";
        if ($res) {
          $msg = "【 $good_name 】，卡密为$res";
          Msg::send(0, $user_id, ['content' => $msg]);
          return success($message);
        } else {
          return error('当前库存不足，请稍后尝试');
        }
        break;
      case 2:
        $userData = User::where('id', $user_id)->find();
        if ($userData['vip_time'] < time()) {
          $vip_time = $data['vip_time'] + time();
        } else {
          $vip_time = $userData['vip_time'] + $data['vip_time'];
        }
        $res = User::where('id', $user_id)->update(['vip_time' => $vip_time]);
        if ($res) {
          $vip = date('Y-m-d H:i:s', $vip_time);
          $message = "恭喜您兑换【 $good_name 】成功 ,你的会员时长将于{$vip}到期！";
          Msg::send(0, $user_id, ['content' => $message]);
          return success($message);
        }
        break;
    }
    return 0;
  }
}
